package com.android.jr_infraredcamera.utils

import android.content.Context
import android.util.Log
import com.kongqw.serialportlibrary.Driver
import com.kongqw.serialportlibrary.SerialUtils
import com.kongqw.serialportlibrary.enumerate.SerialPortEnum
import com.kongqw.serialportlibrary.enumerate.SerialStatus
import com.kongqw.serialportlibrary.listener.SerialPortDirectorListens
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import java.io.File

/**
 * @author 战神族灬小火
 * @date 2025/2/25
 * @description
 */
class SerialPortUtils {
    companion object {
        private const val TAG = "===SerialPortUtils==="
        private var serialPortUtils: SerialPortUtils? = null

        private val instant by lazy { SerialPortUtils() }

        fun getInstance(): SerialPortUtils {
            return instant
        }
    }
     fun initSerialPort(mContext: Context,callBack: SerialCallBack) = CoroutineScope(Dispatchers.IO).launch {
        val list = listOf<Driver>(
            Driver("/dev/ttyS0", "115200"),
//            Driver("/dev/ttyS2", "38400"),
//            Driver("/dev/ttyS3", "38400"),
        )
        with(SerialUtils.getInstance())  {
            manyOpenSerialPort(list)
            setmSerialPortDirectorListens(object : SerialPortDirectorListens {
                override fun onDataReceived(bytes: ByteArray?, serialPortEnum: SerialPortEnum?) {
                    Log.d(TAG, "SerialPort:${serialPortEnum?.name} onDataReceived:${bytes?.toHexString(false)} ")
                    if (bytes != null) {
                        val serialNum = when (serialPortEnum) {
                            SerialPortEnum.SERIAL_ONE -> {

                            }
                            SerialPortEnum.SERIAL_TWO -> {

                            }
                            SerialPortEnum.SERIAL_THREE -> {

                            }

                            else -> {

                            }
                        }
                        callBack.dataCallBack(bytes, serialPortEnum)
                    }
                }

                override fun onDataSent(bytes: ByteArray?, serialPortEnum: SerialPortEnum?) {
                    Log.d(TAG, "SerialPort${serialPortEnum?.name} onDataSent: ${bytes?.toHexString(false)}")
                }

                override fun openState(
                    serialPortEnum: SerialPortEnum?,
                    device: File?,
                    status: SerialStatus?,
                ) {


                    Log.d(TAG, "Serial Port:$serialPortEnum  || OpenState: ${status?.name}")
                    when (status) {
                        SerialStatus.SUCCESS_OPENED -> {

                        }

                        SerialStatus.NO_READ_WRITE_PERMISSION -> {

                        }

                        SerialStatus.OPEN_FAIL -> {

                        }

                        else -> {

                        }
                    }
                }
            })
        }

    }

    interface SerialCallBack {
        fun dataCallBack(data: ByteArray, serialNum: SerialPortEnum?)

        fun onFail(error: Int, msg: String)
    }



    /**
     * 串口发送数据
     */
     suspend fun sendData(serialNum: SerialPortEnum, byteArray: ByteArray, timeOut: Long): Boolean =
        withTimeout(timeOut) {
            Log.e(TAG, "sendData: try send   ${byteArray.size}==data:${byteArray.toHexString(true)}", )
            return@withTimeout SerialUtils.getInstance().sendData(serialNum, byteArray)
        }
}